<?php
/**
 * Q_Rule_Set deals with error messages and holds filters. 
 */
class Q_Filter_Set implements Q_Filter_Interface {

    const ALL = '__ALL__';
    protected $_filters = array();
    /**
     * This is used for arrays of data
     */
    public function filter($data) {
    
        // loop through each field in data and apply the "ALL" filters to it
        if (isset($this->_filters[self::ALL]) && is_array($this->_filters[self::ALL])) {
            foreach ($data as $field => $value) {
                foreach ($this->_filters[self::ALL] as $filter) {
                    // add the filter to the set for given field
                    $this->add($filter, $field);
                }
            }
        }
        // unset it now so loop doesn't try to use "ALL" filters
        unset($this->_filters[self::ALL]);
        // each filter
        foreach ($this->_filters as $field => $filters) {
            foreach ($filters as $filter) {
                if ($filter instanceof Q_Filter_Abstract) {
                    $filter->setField($field);
                }
                $data = $filter->filter($data);
            }
        }
        return $this->_data = $data;
    
    }
    /**
     * Adds a filter / filterset to the filterset
     */
    public function add(Q_Filter_Interface $filter, $fields = null) {
    
        // if you don't specify a field, it applies it to all fields
        if (is_null($fields) || empty($fields)) {
            $fields = array(self::ALL);
        }
        // you can provide a string as $fields and it will apply to that field
        if (is_string($fields)) {
            $fields = array($fields);
        }
        // loop through each field and apply its filter
        foreach ($fields as $key => $field) {
            if (!isset($this->_filters[$field])) $this->_filters[$field] = array();
            $this->_filters[$field][] = $filter;
        }
        return $this;
    
    }

}